package com.txby.wrApi.config;

import javax.sql.DataSource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.ImportResource;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

/**
 * Created by summer on 2016/11/25.
 */
@Configuration
@MapperScan(basePackages = { 
"com.jck.mybatis.mapper" }, sqlSessionTemplateRef = "sqlSession")
public class DataSourceConfig {
	@Bean(name = "sqlserverDataSource")
	@ConfigurationProperties(prefix = "spring.datasource.sqlserver")
	@Primary
	public DataSource sqlserverDataSource() {
		return DataSourceBuilder.create().build();
	}

	@Bean(name = "sqlServerSqlSessionFactory")
	@Primary
	public SqlSessionFactory sqlServerSqlSessionFactory(@Qualifier("sqlserverDataSource") DataSource dataSource)
			throws Exception {
		SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
		bean.setDataSource(dataSource);
		// properties文件已配置，这里可取消
//		bean.setConfigLocation(new ClassPathResource("mybatis/mybatis-config.xml"));
//		bean.setMapperLocations(
//				new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/mapping/*.xml"));
		return bean.getObject();
	}

	@Bean(name = "sqlserverTransactionManager")
	@Primary
	public DataSourceTransactionManager sqlserverTransactionManager(
			@Qualifier("sqlserverDataSource") DataSource dataSource) {
		return new DataSourceTransactionManager(dataSource);
	}

	@Bean(name = "sqlSession")
	@Primary
	public SqlSessionTemplate sqlSession(@Qualifier("sqlServerSqlSessionFactory") SqlSessionFactory sqlSessionFactory)
			throws Exception {
		return new SqlSessionTemplate(sqlSessionFactory);
	}

}
